#include "httpmgr.h"
#include <QNetworkReply>

HttpMgr::HttpMgr()
{
    connect(this,&HttpMgr::sig_http_finish,this,&HttpMgr::slot_http_finish);
}

void HttpMgr::PostHttpReq(const QUrl url,const QJsonObject json,
                          const ReqId req_id,const Modules mod)
{
    /*
1.1构建请求
1.2发送请求
1.3接收发送结果
1.4处理发送结果
    */

    QNetworkRequest request(url);

    //1.1.1构建请求头
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");

    QByteArray data = QJsonDocument(json).toJson();
    //1.1.1构建请求长度
    request.setHeader(QNetworkRequest::ContentLengthHeader,
                      QByteArray::number(data.length()));
    //1.2发送请求
    QNetworkReply *reply =  _manager.post(request,data);

    //1.3接收发送结果

    //获取自己的智能指针，构造伪闭包并增加智能指针引用计数
    auto self = shared_from_this();//自身智能指针

    //这里的lambda表达式捕获this指针是不安全的，整个HttpMgr调用都需要使用智能指针，保证在使用期间不会被提前回收
    QObject::connect(reply, &QNetworkReply::finished, [reply, self, req_id, mod](){
            //处理错误的情况
            if(reply->error() != QNetworkReply::NoError){
                qDebug() << reply->errorString();
                //发送信号通知完成
                emit self->sig_http_finish(req_id, "", ErrorCodes::ERR_NETWORK, mod);

                //回收reply
                reply->deleteLater();
                return;
            }
            //无错误则读回请求
            QString res = reply->readAll();

            qDebug() << res;
            //发送信号通知完成
            emit self->sig_http_finish(req_id, res, ErrorCodes::SUCCESS,mod);
            reply->deleteLater();
            return;
        });
}

void HttpMgr::slot_http_finish(ReqId id, QString str, ErrorCodes er, Modules mod)
{
    if(mod == Modules::REGISTERMOD)
    {
        emit sig_reg_mod_finish(id,str,er);
    }
    else if(mod == Modules::RESETPASSWPRDMOD)
    {
        emit sig_reset_mod_finish(id,str,er);
    }
    else if(mod == Modules::LOGIN)
    {
        emit sig_login_mod_finish(id,str,er);
    }
}
